package com.atguigu.gmall.pay.notify;/*
 * @author: XueYouPeng
 * @time: 23.8.1 下午 6:22
 */

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.atguigu.gmall.pay.properties.AliPayProperties;
import com.atguigu.gmall.rabbit.constant.RabbitConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping(value = "/api/payment/notify")
@Slf4j
public class NotifyOrderStatusController {

    @Autowired
    private AliPayProperties aliPayProperties;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostMapping(value = "/notifyOrderStatus")
    public String notifyOrderStatus(@RequestParam Map<String , String> params) {

        try {

            // 校验数据的合法性
            // Map<String, String> params, String publicKey, String charset, String signType
            boolean rsaCheckResult = AlipaySignature.rsaCheckV1(params, aliPayProperties.getPublicKey(), aliPayProperties.getCharset(), aliPayProperties.getSignType());
            if(rsaCheckResult) {        // 数据是合法的
                log.info("数据合法，params: {} " , JSON.toJSONString(params));

                // 发送消息到mq中
                rabbitTemplate.convertAndSend(RabbitConstant.ORDER_EXCHANGE , RabbitConstant.ORDER_PAYED_ROUTING_KEY ,JSON.toJSONString(params));

                return "success" ;

            }else {
                log.info("数据非法的，params: {} " , JSON.toJSONString(params));
                return "error" ;
            }

        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }

    }
}
